package com.sakiko.dailynote.controller;

import com.sakiko.dailynote.pojo.Result;
import com.sakiko.dailynote.pojo.User;
import com.sakiko.dailynote.service.UserService;
import com.sakiko.dailynote.utils.JwtUtil;
import com.sakiko.dailynote.utils.Md5Util;
import com.sakiko.dailynote.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
//    public Result register(@Pattern(regexp = "^(?:[\\u4e00-\\u9fa5]{2,}|[A-Za-z]{5,})$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
            // 查询用户
            User registerUser = userService.findByUserName(username);
            if(registerUser == null){
                // 没有占用
                // 注册
                userService.register(username,password);
                return Result.success();
            }else{
                // 占用
                return Result.error("用户名已被占用");
            }
    }
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        // 根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        // 判断该用户是否存在
        if(loginUser == null){
            return Result.error("用户名不存在");
        }
        // 判断密码是否正确 loginUser在数据库查询出来的密码是加密的
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            // 登陆成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 把 token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set( token, token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> getUserInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String username =(String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody @Validated User user){ // body的参数刚好和user的对应
        userService.update(user);
        return Result.success("更新用户信息成功");
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){ // 更新头像
        userService.updateAvatar(avatarUrl);
        return Result.success("更新用户头像成功");
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        // 校验参数 【validation满足不了需求就自己写】
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        if(!userService.findByUserName(username).getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码输入错误");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("新密码两次输入不一致");
        }
        // 完成密码更新
        userService.updatePassword(newPwd);
        // 删除 redis中对应的 token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        stringRedisTemplate.delete(token);

        return Result.success("密码更新成功");
    }
}
